package com.kotasoft.iip.processor;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kotasoft.iip.model.insurance.MarketOrder;
import com.kotasoft.iip.model.insurance.Order;
import com.kotasoft.iip.model.insurance.OrderDistribution;
import com.kotasoft.iip.model.interfaces.HasBuyDistribution;
import com.kotasoft.iip.model.interfaces.HasOrder;

public class GenerateMarketOrders implements Processor {

	private static final Logger LOG = LoggerFactory.getLogger(GenerateSendOrders.class);

	public void process(Exchange exchange) throws Exception {
		Order order = exchange.getIn().getMandatoryBody(HasOrder.class).getOrder();
		LOG.debug("Generando market orders {}", order);
		List<MarketOrder> marketOrders = new ArrayList<MarketOrder>();
		if (HasBuyDistribution.class.isAssignableFrom(order.getClass())) {
			HasBuyDistribution hasBuyDistribution = (HasBuyDistribution) order;
			BigDecimal orderAmount = order.getNetAmount();
			BigDecimal totalAmount = BigDecimal.ZERO;
			for (Iterator<OrderDistribution> iterator = hasBuyDistribution.getBuyDistribution().iterator(); iterator.hasNext();) {
				OrderDistribution orderDistribution = iterator.next();
				BigDecimal partialAmount;
				if (iterator.hasNext()) {
					partialAmount = orderAmount.multiply(orderDistribution.getPercent()).divide(new BigDecimal("100"), 2, RoundingMode.HALF_EVEN);
					totalAmount = totalAmount.add(partialAmount);
				} else {
					partialAmount = orderAmount.subtract(totalAmount);
				}
				MarketOrder marketOrder = new MarketOrder();
				marketOrder.setAmount(partialAmount);
				marketOrder.setAsset(orderDistribution.getAsset());
				marketOrders.add(marketOrder);
			}
		}
		order.setMarketOrders(marketOrders);
	}
}
